package com.shoeshopping.service.zx;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.shoeshopping.dao.BaseDao;
import com.shoeshopping.entity.Admin;
import com.shoeshopping.formbean.zx.AdminForm;
import com.shoeshopping.utils.zx.HttpSessionUtil;

@Transactional
@Service("adminService")
public class AdminServiceImpl implements AdminService {

	@Resource
	BaseDao baseDao;

	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public boolean login(AdminForm dataForm) {
		String hql = "from Admin as a where a.username = ? and a.password = ?";
		List param = new ArrayList();
		param.add(dataForm.getUsername());
		param.add(dataForm.getPassword());
		System.out.println("hql = " + hql);
		List list = baseDao.find(hql,param);
		if (list.size() > 0) {
			Admin admin = (Admin) list.get(0);
			HttpSessionUtil.shareHttpSessionUtil().addAdmin(admin);
			return true;
		}

		return false;
	}

	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public boolean logout() {
		HttpSessionUtil.shareHttpSessionUtil().removeAdmin();
		return true;
	}

	@Override
	public boolean changePassword(AdminForm dataForm) {
		String password = dataForm.getPassword().trim();
		String rePassword = dataForm.getRePassword().trim();
		String newPassword = dataForm.getNewPassword().trim();
		
		if (password == null || rePassword == null || newPassword == null) {
			return false;
		}
		
		if (!newPassword.equals(rePassword)) {
			return false;
		}
		
		String id = HttpSessionUtil.shareHttpSessionUtil().getAdminId();
		
		String hql = "from Admin as a where " + "a.id = '"+ id + "'";
		System.out.println("hql = " + hql);
		
		List list = baseDao.find(hql);
		if (list.size() > 0) {
			Admin admin = (Admin) list.get(0);
			if(admin.getPassword().equals(password)){
				admin.setPassword(newPassword);
				baseDao.update(admin);
				return true;
			}
		}
		
		return false;
	}

}
